const _request = require("../../utils/request.js");
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: [1, 2, 3],
    userId: '',
    mallimgUrl: app.globalData.mallimgUrl
  },

  del(event) {
    const self = this
    wx.showModal({
      title: '',
      content: '确定要删除这条地址吗',
      success (res) {
        if (res.confirm) {
          self.handleDel(event)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  handleDel(event) {
    const self = this
    _request.get('/receiveAndDeliver/deleteReceiveAndDeliverAddressById', {
      id: event.currentTarget.dataset.id
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 1000
        })
        let list = self.data.addressList
        let ind = -1
        list.forEach((e, index) => {
          if (e.id == event.currentTarget.dataset.id) {
            ind = index
          }
        })
        if (ind > -1) {
          list.splice(ind, 1)
          self.setData({
            addressList: list
          })
        }
      }
    })
  },

  query() {
    const self = this
    _request.get('/receiveAndDeliver/getReceiveAndDeliverAddressByUserId', {
      id: this.data.userId
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        self.setData({
          addressList: res.data.data.rows || []
        })
      }
    })
  },

  gotoAdd() {
    wx.navigateTo({
      url: '/pages/shopingmall/addressadd'
    })
  },

  edit(event){
    const id = event.currentTarget.dataset.id
    const list = this.data.addressList
    wx.navigateTo({
      url: '/pages/shopingmall/addressadd?data=' + JSON.stringify(list.filter(e => e.id == id)[0])
    })
  },

  selectAddress(event) {
    const id = event.currentTarget.dataset.id
    const list = this.data.addressList
    wx.setStorageSync('_shopmalladdress', JSON.stringify(list.filter(e => e.id == id)[0]))
    wx.navigateBack({
      delta: 0,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userId: wx.getStorageSync('userId')
    })
    this.query()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.query()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})